package com.leyou.user.controller;

import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.dto.AddressDTO;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data,
                                             @PathVariable("type") Integer type){
        Boolean result = userService.checkData(data,type);
        return ResponseEntity.ok(result);
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
        userService.sendVerifyCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user,
                                         BindingResult result,//此对象要紧挨着需要被校验的对象
                                         @RequestParam("code") String code){
        if(result.hasErrors()){
            String errorStr = result.getFieldErrors()
                    .stream()
                    .map(FieldError::getDefaultMessage)

                    .collect(Collectors.joining("|"));
            throw new LyException(400,errorStr);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 查询用户名和密码
     */
    @GetMapping("/query")
    public ResponseEntity<User> findUserByUserNameAndPwd(
            @RequestParam("username") String username,@RequestParam("password") String password
    ) {
        User loginUser = userService.findUserByUserNameAndPwd(username,password);
        return ResponseEntity.ok(loginUser);
    }
    // 在IOC里不能有相同名字的bean,否则其中一个无法加载到IOC中

    /**
     * 查询下订单时用户的收货地址
     */
    @GetMapping("/address")
    public ResponseEntity<AddressDTO> findAddressById(
            @RequestParam("userId") Long userId,
            @RequestParam("id") Long id
    ){
        AddressDTO addressDTO = userService.findAddressById(userId,id);
        return ResponseEntity.ok(addressDTO);
    }
}
